<?php
	class FacebookUsersController extends AppController
	{
		var $name = "FacebookUsers";
		
		
		function register()
		{
			$UserModel = $UserModel =  cri("Sociable.FacebookConfig")->getUserModel();
			//ie user is logged in
			$back = "/";
			if(isset($this->params['named']['back']))
			{
				$back = base64_decode($this->params['named']['back']);
					
			} 
			if($this->Session->read("Auth.".$UserModel->alias))
			{
				$this->redirect("/");
			}
			$fbUserId = FacebookApi::getInstance()->getUser();
			if(!$fbUserId || $this->FacebookUser->isUserRegistered($fbUserId))
			{
				$this->redirect($back);
			}
			$fbInfo = FacebookApi::getInstance()->api('/me');
			$this->set("fbInfo",$fbInfo);
			callHooks("OnFaceBookRegister",'.+',$this,$fbInfo,$UserModel);
			//ie skip validation and only registers.
			if(cr("Facebook.directRegister") == true)
			{
				if($this->FacebookUser->registerByFbId($fbUserId))
				{
					$this->redirect($back);
				}else
				{
					$this->errorMsg(__("There was some problem while connecting with facebook. Please try later."));
					$this->redirect('/');
				}
			}else
			{
				$UserModel = cri('FacebookConfig')->getUserModel();
				if($this->data)
				{
					if($this->FacebookUser->registerUser($fbUserId,$this->data[$UserModel->alias]))
					{
						$this->redirect($back);
					}else
					{
						$this->errorMsg(__("Please correct errors in form below and then try again."));
					}
				}
				if(!$this->data)
				{
					$this->data[$UserModel->alias] = $this->FacebookUser->getFbRegisterData($fbUserId,$fbInfo);
				}
			}
			$this->helpers[] = "Form";
		}
        
        function channel()
        {
          Configure::write("debug",0);
          $cache_expire = 60*60*24*365;
          header("Pragma: public");
           header("Cache-Control: max-age=".$cache_expire);
           header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
           echo '<script src="//connect.facebook.net/en_US/all.js"></script>';
           exit;
        }
	}
?>